const http = require("http");
const url = require('url');
const path = require("path");
const ejs = require("ejs");
const MongoClient = require("mongodb").MongoClient;
const require1 = require(path.join(__dirname, "express-rout"));

const mongodbUrl = "mongodb://127.0.0.1:27017";
//  数据库名称
const dbName = "aaa";
http.createServer(require1).listen(8001);

require1.get("/", function (req, res) {
    const list =[];

    MongoClient.connect(mongodbUrl, {useNewUrlParser: true}, function (err, client) {

        const collection = client.db("aaa").collection("user");
        const result = collection.find();
        result.each(function (err, doc) {
            if (doc!=null){
                list.push(doc)
            } else {
                console.log(list);
            }
        })
    })
});
require1.get("/add", function (req, res) {
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});

    MongoClient.connect(mongodbUrl, {useNewUrlParser: true}, function (err, client) {

        const collection = client.db("aaa").collection("user");
        collection.insertOne({"aaaaaaaa": 2222222}, function (err, result) {
            if (err) {
                res.end("插入数据失败");
                return;
            }
            client.close();
            res.end("增加数据成功");
        })
    })
});
require1.get("/edit", function (req, res) {
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
    MongoClient.connect(mongodbUrl, {useNewUrlParser: true}, function (err, client) {

        const collection = client.db("aaa").collection("user");


        collection.updateOne({"aaaaaaaa": 2222222}, {
            $set: {
                "age": 60
            }
        }, function (err, result) {
            if (err) {
                res.end("修改数据失败");
                return;
            }
            client.close();
            res.end("修改数据成功");
        })
    })
});
require1.get("/delete", function (req, res) {
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
    MongoClient.connect(mongodbUrl, {useNewUrlParser: true}, function (err, client) {

        const collection = client.db("aaa").collection("user");


        collection.deleteOne({"aaaaaaaa": 2222222},  function (err, result) {
            if (err) {
                res.end("删除数据失败");
                return;
            }
            client.close();
            res.end("删除数据成功");
        })
    })
});


